/*
 * ------------------------------------------------------------------
 * 数据格式化模块
 * ------------------------------------------------------------------
 * @关于我：
 * QQ:2815473064
 * wechat:13531609457
 * ------------------------------------------------------------------
 */
const DayJs = require("dayjs");
// 格式化数据转成VueRouter格式
exports.formatMenusList = (list) => {
  return list
    .filter((menu) => menu.name)
    .map((item) => {
      let {
        type,
        name,
        path,
        id,
        pid,
        title,
        component,
        icon_normal,
        icon_normal_color,
        icon_active,
        icon_active_color,
        icon_right_arrow,
        breadcrumbs_show,
        navigator_show,
        redirect_target,
        redirect_url,
        redirect_type,
        redirect_state,
        redirect_name,
        update,
        remove,
        buoy,
        sort_top,
        sort_index,
        state
      } = item;
      return {
        name,
        path,
        redirect: null,
        component,
        children: [],
        meta: {
          id: Number(id),
          type: Number(type),
          pid: pid <= 0 ? null : Number(pid),
          title,
          parent: null,
          Buoy: buoy == 0 ? null : buoy, // 徽标
          Storey: 0,// 菜单层级
          RightArrow: Boolean(icon_right_arrow), // 显示右侧箭头
          Breadcrumb: Boolean(breadcrumbs_show), // 面包屑显示
          Navigator:  Boolean(navigator_show), // 导航菜单显示
          IconNavigator:true,// 图标导航菜单显示
          childrenDevelop: false, // 子菜单是否展开
          index: Number(sort_index), // 排序Index
          SortTop: Boolean(sort_top), // 置顶
          SkipRouter: null,
          SkipTarget: null, // 重定向方式
          icon: {
            normal: icon_normal, // 正常状态图标
            normal_color: icon_normal_color, // 正常状态图标颜色
            active: icon_active, // 激活状态图标
            active_color: icon_active_color, // 激活状态图标颜色
            right_arrow: icon_right_arrow, // 当为菜单时，显示右侧箭头
          },
          display: {
            breadcrumb: breadcrumbs_show ?? true, // 面包屑显示
            navigator: navigator_show ?? true, // 导航菜单显示
            activedChangeId: null, // 当菜单激活时,将激活的ID指向这个ID，用于高亮其他ID的菜单
            childrenDevelop: false, // 子菜单是否展开
          },
          keepAlive: {},
          redirect: {
            redirect_target, // 重定向跳转方式（0：内跳转  1：外页）
            redirect_url, // 重定向跳转菜单/网页地址
            redirect_type, // 重定向方式（1菜单重定向  0地址重定向）
            redirect_state, // 重定向开启（0：不开启 1：开启）
            redirect_name, // 重定向跳转菜单name
          },
          update: Boolean(update),
          remove: Boolean(remove),
          state
        },
      };
    });
};
// 格式化转树结构
exports.formatTreeList = (list) => {
  let result = [];
  let map = {};
  list.forEach((item) => {
    map[item.meta.id] = item;
  });
  list.forEach((item) => {
    let parent = map[item.meta.pid];
    if (parent) {
      map[item.meta.pid].children.push(item);
    } else {
      result.push(item);
    }
  });
  return result;
}


// 格式化custom数组
exports.formatCustomList = (list) => {
  let groupList = [];
  let groupObject = {};
  // 筛除group组
  for (let item of list) {
    let { group_id } = item;
    let exist = groupList.some((item) => item.group_id == group_id);
    if (!exist) {
      groupList.push(item);
    }
  }
  // 格式化group数组
  groupList = groupList.map((item) => {
    let {
      group_id,
      group_title,
      comment,
      group_update,
      group_show,
      group_key,
    } = item;
    let obj = {
      id: group_id,
      key: group_key,
      title: group_title,
      setting: {},
      comment: comment,
      update: Boolean(Number(group_update)),
      show: Boolean(Number(group_show)),
    };
    list.forEach((listItem) => {
      if (listItem.group_id == group_id) {
        obj.setting[listItem.name] = {
          label: listItem.label,
          labelconfig: {
            type: listItem.type,
            update: Boolean(Number(listItem.update)),
            show: Boolean(Number(listItem.show)),
          },
          meta: {},
          value: listItem.value,
          option: [],
        };
      }
    });
    return obj;
  });
  groupList.forEach((item) => {
    groupObject[item.key] = item;
  });
  return groupObject;
};
// 转布尔值
exports.toBoolean = (value) => {
  return Boolean(Number(value));
};
// 格式化用户数据
exports.formatUserList = (userArray, deletePassword = false) => {
  try {
    return userArray.map((item) => {
      let {
        id,
        reliable,
        mark,
        role,
        new_role,
        inviter,
        inviter_code,
        avatar,
        introduce,
        nickname,
        username,
        password,
        gender,
        wechat,
        mobile,
        qq,
        email,
        address_province,
        address_cities,
        address_districts,
        address_town,
        address_detail,
        address_map_longitude,
        address_map_latitude,
        super_admin,
        register_time,
        register_ip,
        // register_date,
        register_device,
        register_ip_location,
        last_login_time,
        last_login_ip,
        last_login_device,
        // last_login_date,
        last_login_ip_location,
        last_login_token_expired_date,
        mobile_bind_time,
        wechat_bind_time,
        email_bind_time,
        qq_bind_time,

        mobile_bind_status,
        wechat_bind_status,
        eamil_bind_status,
        qq_bind_status,
        birth_year,
        birth_month,
        birth_day,
        option_auth,
        id_card_back,
        id_card_front,
        id_card_in_hand,
        identity,
        license,

        security_state,
        security_answer1,
        security_response1,
        security_answer2,
        security_response2,
        security_answer3,
        security_response3,
        security_set_date,
        real_refuse_after,
        real_status, // 认证状态
        real_result,
        real_state,
        real_type, // 认证类型
        real_info, // 认证资料
        real_date, // 提交认证时间
        real_pass_date, // 认证通过时间
        real_pass_reason, // 认证通过理由
        real_error_reason, // 认证拒绝理由
        real_error_date, // 认证拒绝时间
        real_comment, // 认证备注

        restrict_login_state,
        restrict_login_date,
        reliable_date,
        comment,
        state,
      } = item;
      // 现在的时间戳
      let now_date = DayJs(Date.now());
      let register_date = DayJs(register_time);
      let last_login_date = DayJs(last_login_time);
      item = {
        id: Number(id),
        reliable: Boolean(Number(reliable)),
        mark,
        role: Number(role),
        new_role,
        inviter, //
        inviter_code, // 邀请码
        avatar, // 头像
        introduce,
        nickname,
        username,
        password,
        gender: Number(gender),
        super_admin: Boolean(Number(super_admin)),
        register_info: {
          date: register_time, // 注册时间
          ip: register_ip, // 注册IP
          device: register_device, // 注册端口
          diff_now_day: Math.abs(register_date.diff(now_date, "day")),
          ip_location: register_ip_location,
        },
        birth_year,
        birth_month,
        birth_day,
        birth_text: `${birth_year}-${birth_month}-${birth_day}`,
        wechat,
        mobile,
        qq,
        email,
        mobile_bind_status: Boolean(Number(mobile_bind_status)),
        wechat_bind_status: Boolean(Number(wechat_bind_status)),
        eamil_bind_status: Boolean(Number(eamil_bind_status)),
        qq_bind_status: Boolean(Number(qq_bind_status)),
        contact: {
          wechat,
          mobile,
          qq,
          email,
          mobile_bind_time,
          wechat_bind_time,
          email_bind_time,
          qq_bind_time,
          mobile_bind_status: Boolean(Number(mobile_bind_status)),
          wechat_bind_status: Boolean(Number(wechat_bind_status)),
          eamil_bind_status: Boolean(Number(eamil_bind_status)),
          qq_bind_status: Boolean(Number(qq_bind_status)),
        },
        // 认证信息
        real_refuse_after: Boolean(Number(real_refuse_after)),
        real_state: Number(real_state),
        real_type: Number(real_type), // 认证类型
        real_info: real_info ?? {}, // 认证资料
        real_result: Number(real_result), // 认证结果
        real_date, // 提交认证时间
        real_pass_date, // 认证通过时间
        real_pass_reason, // 认证通过理由
        real_error_reason, // 认证拒绝理由
        real_error_date, // 认证拒绝时间
        real_comment, // 认证备注

        // 最后登录信息
        last_login_time,
        last_login_ip,
        // 注册信息
        register_time,
        register_ip,
        // 所在城市
        address_province,
        address_cities,
        address_districts,
        address_town,
        address_detail,
        address_map_longitude,
        address_map_latitude,
        // 密保问题
        security_state: Boolean(Number(security_state)),
        security_answer1,
        security_response1,
        security_answer2,
        security_response2,
        security_answer3,
        security_response3,
        security_set_date,
        restrict_login_state: Boolean(Number(restrict_login_state)),
        restrict_login_date,
        // 临时用户到期时间
        reliable_date,
        // 备注
        comment,
        // 状态
        state,
      };
      return item;
    });
  } catch (error) {
    console.log(error);
    console.log("格式化用户数据失败,", error);
    throw { code: 500, msg: "格式化数据失败" };
  }
};
// 格式化用户角色数组
exports.formatRolesArray = (roleArray, mergeRoleArray = null) => {
  // 数据格式检验
  if (mergeRoleArray && Array.isArray(mergeRoleArray)) {
    mergeRoleArray.filter((item) => {
      let type = typeof item;
      if (type == "object") {
        let { role_id, create_date } = item;
        if (role_id && create_date) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    });
  } else {
    mergeRoleArray = [];
  }
  // 数据格式检验
  roleArray = roleArray.filter((item) => {
    let type = typeof item;
    if (type == "number" || type == "string") {
      return true;
    } else {
      return false;
    }
  });
  // 去掉已存在的角色数据
  roleArray = roleArray
    .filter((i) => !mergeRoleArray.some((a) => a.role_id == i))
    .map((role_id) => {
      let date_now = DayJs(Date.now()).valueOf();
      return {
        role_id,
        create_date: date_now,
      };
    });

  if (roleArray.length) {
    // 合并现有数据
    mergeRoleArray = mergeRoleArray.concat(roleArray);
    return mergeRoleArray;
  } else {
    return mergeRoleArray;
  }
};
